// pages/statistics/statistics.js
Page({
  data: {
    // 用户统计数据
    userStats: {
      totalOperations: 156,
      totalTokenConsumed: 156,
      favoriteCount: 23,
      categoryCount: 5,
      lastOperationTime: '2025-01-31 15:30:00'
    },

    // 图表尺寸
    chartWidth: 300,
    chartHeight: 200,

    // 最近操作记录
    recentRecords: [
      {
        id: 1,
        operationType: 'changeClothes',
        operationDesc: '虚拟换装操作',
        tokenCost: 1,
        createTime: '2025-01-31 15:30:00'
      },
      {
        id: 2,
        operationType: 'faceSwap',
        operationDesc: 'AI换脸操作',
        tokenCost: 1,
        createTime: '2025-01-31 14:20:00'
      },
      {
        id: 3,
        operationType: 'changeBackground',
        operationDesc: '背景更换操作',
        tokenCost: 1,
        createTime: '2025-01-31 13:15:00'
      },
      {
        id: 4,
        operationType: 'changeClothes',
        operationDesc: '虚拟换装操作',
        tokenCost: 1,
        createTime: '2025-01-31 12:45:00'
      },
      {
        id: 5,
        operationType: 'faceSwap',
        operationDesc: 'AI换脸操作',
        tokenCost: 1,
        createTime: '2025-01-31 11:30:00'
      }
    ],

    // 成就系统
    achievements: [
      {
        id: 1,
        name: '换装新手',
        description: '完成首次虚拟换装',
        icon: '🎯',
        unlocked: true,
        progress: 100,
        current: 1,
        target: 1
      },
      {
        id: 2,
        name: '时尚达人',
        description: '完成50次换装操作',
        icon: '👗',
        unlocked: true,
        progress: 100,
        current: 50,
        target: 50
      },
      {
        id: 3,
        name: '换脸专家',
        description: '完成20次换脸操作',
        icon: '👤',
        unlocked: false,
        progress: 75,
        current: 15,
        target: 20
      },
      {
        id: 4,
        name: '收藏家',
        description: '收藏30件商品',
        icon: '❤️',
        unlocked: false,
        progress: 60,
        current: 18,
        target: 30
      }
    ],

    // 趋势数据
    trendData: {
      mostActiveTime: '14:00-16:00',
      preferredStyle: '休闲风格',
      frequency: '3.2次/天'
    },

    // 图表数据
    usageData: [12, 19, 15, 25, 22, 18, 28], // 最近7天使用次数
    distributionData: [
      { name: '虚拟换装', value: 45, color: '#ff6b9d' },
      { name: 'AI换脸', value: 25, color: '#4ecdc4' },
      { name: '背景更换', value: 20, color: '#45b7d1' },
      { name: '其他操作', value: 10, color: '#96ceb4' }
    ]
  },

  onLoad() {
    console.log('统计页面加载');
    this.initChartSize();
    this.loadUserStatistics();
    
    // 延迟绘制图表，确保页面渲染完成
    setTimeout(() => {
      this.drawUsageChart();
      this.drawDistributionChart();
    }, 500);
  },

  // 初始化图表尺寸
  initChartSize() {
    const systemInfo = wx.getSystemInfoSync();
    const chartWidth = Math.min(systemInfo.windowWidth - 80, 600);
    const chartHeight = chartWidth * 0.6;
    
    this.setData({
      chartWidth: chartWidth,
      chartHeight: chartHeight
    });
  },

  // 加载用户统计数据
  loadUserStatistics() {
    // 这里应该调用真实的API获取用户统计数据
    // 现在使用模拟数据
    console.log('加载用户统计数据...');
  },

  // 绘制使用情况图表（折线图）
  drawUsageChart() {
    const ctx = wx.createCanvasContext('usageChart', this);
    const { chartWidth, chartHeight, usageData } = this.data;
    
    // 设置画布背景
    ctx.setFillStyle('#ffffff');
    ctx.fillRect(0, 0, chartWidth, chartHeight);
    
    // 计算绘图区域
    const padding = 40;
    const plotWidth = chartWidth - 2 * padding;
    const plotHeight = chartHeight - 2 * padding;
    
    // 绘制坐标轴
    ctx.setStrokeStyle('#e0e0e0');
    ctx.setLineWidth(1);
    
    // Y轴
    ctx.beginPath();
    ctx.moveTo(padding, padding);
    ctx.lineTo(padding, chartHeight - padding);
    ctx.stroke();
    
    // X轴
    ctx.beginPath();
    ctx.moveTo(padding, chartHeight - padding);
    ctx.lineTo(chartWidth - padding, chartHeight - padding);
    ctx.stroke();
    
    // 绘制数据线
    const maxValue = Math.max(...usageData);
    const stepX = plotWidth / (usageData.length - 1);
    
    ctx.setStrokeStyle('#ff6b9d');
    ctx.setLineWidth(3);
    ctx.beginPath();
    
    usageData.forEach((value, index) => {
      const x = padding + index * stepX;
      const y = chartHeight - padding - (value / maxValue) * plotHeight;
      
      if (index === 0) {
        ctx.moveTo(x, y);
      } else {
        ctx.lineTo(x, y);
      }
      
      // 绘制数据点
      ctx.setFillStyle('#ff6b9d');
      ctx.beginPath();
      ctx.arc(x, y, 4, 0, 2 * Math.PI);
      ctx.fill();
    });
    
    ctx.stroke();
    
    // 绘制标签
    ctx.setFillStyle('#666666');
    ctx.setFontSize(12);
    ctx.setTextAlign('center');
    
    const days = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
    days.forEach((day, index) => {
      const x = padding + index * stepX;
      ctx.fillText(day, x, chartHeight - 10);
    });
    
    ctx.draw();
  },

  // 绘制分布饼图
  drawDistributionChart() {
    const ctx = wx.createCanvasContext('distributionChart', this);
    const { chartWidth, chartHeight, distributionData } = this.data;
    
    // 设置画布背景
    ctx.setFillStyle('#ffffff');
    ctx.fillRect(0, 0, chartWidth, chartHeight);
    
    // 计算饼图参数
    const centerX = chartWidth / 2;
    const centerY = chartHeight / 2;
    const radius = Math.min(chartWidth, chartHeight) / 3;
    
    // 计算总值
    const total = distributionData.reduce((sum, item) => sum + item.value, 0);
    
    let currentAngle = -Math.PI / 2; // 从顶部开始
    
    distributionData.forEach((item, index) => {
      const sliceAngle = (item.value / total) * 2 * Math.PI;
      
      // 绘制扇形
      ctx.setFillStyle(item.color);
      ctx.beginPath();
      ctx.moveTo(centerX, centerY);
      ctx.arc(centerX, centerY, radius, currentAngle, currentAngle + sliceAngle);
      ctx.closePath();
      ctx.fill();
      
      // 绘制标签
      const labelAngle = currentAngle + sliceAngle / 2;
      const labelX = centerX + Math.cos(labelAngle) * (radius + 30);
      const labelY = centerY + Math.sin(labelAngle) * (radius + 30);
      
      ctx.setFillStyle('#333333');
      ctx.setFontSize(12);
      ctx.setTextAlign('center');
      ctx.fillText(item.name, labelX, labelY);
      ctx.fillText(`${item.value}%`, labelX, labelY + 15);
      
      currentAngle += sliceAngle;
    });
    
    ctx.draw();
  },

  // 刷新统计数据
  refreshStatistics() {
    wx.showLoading({
      title: '刷新中...'
    });
    
    // 模拟API调用
    setTimeout(() => {
      this.loadUserStatistics();
      this.drawUsageChart();
      this.drawDistributionChart();
      
      wx.hideLoading();
      wx.showToast({
        title: '刷新成功',
        icon: 'success'
      });
    }, 1000);
  }
});
